/* 
for some unknown reasons, this project cannot run in VS2008 but have to run in cmd line
*/

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>

#include "MatWork.hpp"

using namespace std;
using namespace cv;

/// Global Variables
Mat img, ref; 
Mat templ; 
Mat result;
char* ref_wind = "Reference Image";
char* img_wind = "Image Window";
char* result_window = "Result Window";
Rect sel_wind;

int match_method;
int max_Trackbar = 5;
int new_templ = 0;

/// Function Headers
void MatchingMethod( Mat templ, Mat img );
//void MatchingMethod( int, void* );

void onMouse( int event, int x, int y, int, void*  );

float scale = .25;

/** @function main */
int main( int argc, char** argv )
{
  /// Load image and template
  //ref = imread( "pattern1.bmp", 1 );
  //img = imread( "pattern2.bmp", 1 );
  ref = imread( "Picture 48.jpg", 1 );
  img = imread( "Picture 49.jpg", 1 );

  //imshow(img_wind, img);
  //imshow(ref_wind, ref);
  //waitKey(0);
  //return 1;

  //resize(ref, ref, Size(), scale, scale, INTER_LINEAR);
  //resize(img, img, Size(), scale, scale, INTER_LINEAR);
 
  /// Create windows
  namedWindow( ref_wind, CV_WINDOW_AUTOSIZE );
  namedWindow( result_window, CV_WINDOW_AUTOSIZE );

  // Create mouse event
  setMouseCallback( ref_wind, onMouse, NULL );

  /// Create Trackbar
  //char* trackbar_label = "Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED";
  //createTrackbar( trackbar_label, ref_wind, &match_method, max_Trackbar, MatchingMethod );


	// interface code
	int cmd = 0;
	char c;
	while (1)
	{
		imshow( ref_wind, ref);

		if (cmd == 1)
		{
			//MatchingMethod( 0, 0 );
			MatchingMethod( templ, img );

			cmd = 0;
		};

		if (new_templ == 1)
		{
			imshow( "Selected Template", templ);
			//imshow( "Selected Template", templ);
		}

		c = waitKey(0);
		if (c == 27)
		{
			break;
		} else
			if (c == 'p')  // processing
			{
				cmd = 1;
			}

	}

  return 0;
}


// What is going on in this reference list??
void onMouse( int event, int x, int y, int, void*  )
{
	
	 if( event == EVENT_LBUTTONDOWN )
	 {
		sel_wind.x = x;
		sel_wind.y = y;

		//printf("(%d,%d)",x,y);
	
	 } else
		 if( event == EVENT_LBUTTONUP )
			{
				sel_wind.width = x - sel_wind.x + 1;
				sel_wind.height = y - sel_wind.y + 1;		

				new_templ = 1;
				templ = Mat::zeros(sel_wind.height, sel_wind.width, CV_8UC3);
				img(sel_wind).copyTo(templ);
				printf("(%d,%d)",x,y);

			};

	 return;
}



/**
 * @function MatchingMethod
 * @brief Trackbar callback -> restricted function working on global variable
 */
//void MatchingMethod( int, void* )
void MatchingMethod( Mat templ, Mat img )
{
  /// Source image to display
  Mat img_display;
  img.copyTo( img_display );
  Mat mask;

  Mat result;
  int match_method = CV_TM_SQDIFF;



  /// Create the result matrix
  int result_cols =  img.cols - templ.cols + 1;
  int result_rows = img.rows - templ.rows + 1;

  result.create( result_cols, result_rows, CV_32FC1 );

  /// Do the Matching and Normalize
  matchTemplate( img, templ, result, match_method );
  normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );

  /// Localizing the best match with minMaxLoc
  double minVal; double maxVal; Point minLoc; Point maxLoc;
  Point matchLoc;

  minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, mask );

  /// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
  if( match_method  == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
    { matchLoc = minLoc; }
  else
    { matchLoc = maxLoc; }

  /// Show me what you got
  printf("Location: (%d,%d)\n",matchLoc.x,matchLoc.y);
  MATmtxdisp(mask);

  rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
  rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );

  imshow( ref_wind, img_display );
  imshow( result_window, result );

  return;
}